<?php

namespace app\result;

use app\model\Help;

class HelpResult extends BaseResult
{
    public function list_api($args = [])
    {
        $data = (new Help())->data_list_nopage([], '*', 'sort desc,id asc');
        if ($data) {
            foreach ($data as &$item) {
                $item['content'] = htmlspecialchars_decode($item['content']);
            }
            unset($item);
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }

    public function list($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['title', 'like', '%' . trim($args['keyword']) . '%'];
        }
        $model = new Help();
        $total = $model->data_count($where);
        $data = $model->data_list($where, 'id,content,title', 'id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$item) {
                $item['content'] = mb_substr(strip_tags(htmlspecialchars_decode($item['content'], true)), 0, 200) . '...';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = [])
    {
        $id = intval($args['id'] ?? 0);
        $model = new Help();
        $data = $model->data_get(['id' => $id]);
        $data['content'] = htmlspecialchars_decode($data['content']);
        return $this->success_return('success', $data);
    }

    public function save_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        $model = new Help();
        $baseData = [
            'title' => $args['title'],
            'content' => $args['content'],
            'sort' => intval($args['sort'] ?? 0)
        ];
        if ($id) {
            $model->data_update(['id' => $id], $baseData);
        } else {
            $model->data_add($baseData);
        }
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        $model = new Help();
        $res = $model->data_del(['id' => $id]);
        return $this->success_return('success');
    }
}
